package com.weixing.mall.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.provider.api.model.vo.RoleVo;
import com.weixing.mall.provider.api.service.SysUserRpcService;
import com.weixing.mall.provider.mapper.AgentBonusIssueMapper;
import com.weixing.mall.provider.model.domain.AgentAccount;
import com.weixing.mall.provider.model.domain.AgentAccountBill;
import com.weixing.mall.provider.model.domain.AgentBonus;
import com.weixing.mall.provider.model.domain.AgentBonusIssue;
import com.weixing.mall.provider.model.dto.AgentBonusIssueDto;
import com.weixing.mall.provider.model.enums.AgentWithdrawAuditEnum;
import com.weixing.mall.provider.model.enums.BillTransTypeEnum;
import com.weixing.mall.provider.model.enums.BillTypeEnum;
import com.weixing.mall.provider.model.query.AgentBonusIssueQuery;
import com.weixing.mall.provider.model.query.AgentBonusQuery;
import com.weixing.mall.provider.model.vo.AgentBonusIssueVo;
import com.weixing.mall.provider.model.vo.AgentBonusVo;
import com.weixing.mall.provider.service.IAgentAccountBillService;
import com.weixing.mall.provider.service.IAgentAccountService;
import com.weixing.mall.provider.service.IAgentBonusIssueService;
import com.weixing.mall.provider.service.IAgentBonusService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Small
 * @since 2020-07-20
 */
@Service
public class AgentBonusIssueServiceImpl extends ServiceImpl<AgentBonusIssueMapper, AgentBonusIssue> implements IAgentBonusIssueService {
    @Autowired
    private SysUserRpcService sysUserRpcService;
    @Autowired
    private IAgentBonusService agentBonusService;
    @Autowired
    private IAgentAccountService agentAccountService;
    @Autowired
    private IAgentAccountBillService agentAccountBillService;

    @Override
    public IPage<AgentBonusIssue> bounsList(Page page, AgentBonusIssueQuery agentBonusIssueQuery) {
        return null;
    }

    @Override
    public IPage<AgentBonusIssueVo> selectListOfPage(Page page, AgentBonusIssueQuery agentBonusIssueQuery, SysAuth auth) {

        if (auth != null) {
            Long uid = auth.getUid();
            List<RoleVo> list = sysUserRpcService.getRoleById(uid).getData();
            for (RoleVo vo : list) {
                if (vo.getRoleCode().equals(GlobalConstant.RoleCode.ADMIN)) {
                    return baseMapper.selectListOfPage(page, agentBonusIssueQuery);
                }
            }
            for (RoleVo vo : list) {
                if (vo.getRoleCode().equals(GlobalConstant.RoleCode.KFADMIN)) {
                    return baseMapper.selectListOfPage(page, agentBonusIssueQuery);
                }
            }
            agentBonusIssueQuery.setCustomerId(uid.intValue());

        }
        return baseMapper.selectListOfPage(page, agentBonusIssueQuery);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void audit(SysAuth auth, AgentWithdrawAuditEnum auditResult, Long id, String remark) {
        AgentBonusIssue issue = getById(id);
        issue.setAuditTime(new Date());
        issue.setOperator(auth.getUid());
        issue.setAuditResult(auditResult.getValue());
        issue.setAuditReamrk(remark);
        updateById(issue);
        if (auditResult.getValue().intValue() == AgentWithdrawAuditEnum.ADOPT.getValue().intValue()) {
            /*更新分红列表*/
            UpdateWrapper<AgentBonus> ew = new UpdateWrapper<>();
            ew.lambda().set(AgentBonus::getOperationId, auth.getUid())
                    .set(AgentBonus::getOperationTime, LocalDateTime.now())
                    .set(AgentBonus::getOpertaionName, auth.getRealName())
                    .set(AgentBonus::getIsPay, WhetherEnum.YES.getValue())
                    .set(AgentBonus::getOperationStatus, AgentWithdrawAuditEnum.ADOPT.getValue())
                    .eq(AgentBonus::getOutBillId, id);
            agentBonusService.update(ew);
            /*更新代理商账户可用分红金额*/
            AgentAccount agentAccount = agentAccountService.findByAgentId(issue.getAgentId());
            BigDecimal avaBonusRevenue = agentAccount.getAvaBonusRevenue().subtract(issue.getPayAmount());
            agentAccount.setAvaBonusRevenue(avaBonusRevenue);
            agentAccountService.updateById(agentAccount);
            AgentAccountBill bill=new AgentAccountBill();
            bill.setAgentId(issue.getAgentId());
            bill.setAmount(issue.getAmount());
            bill.setBillType(BillTypeEnum.OUTCOME.getValue());
            bill.setCreatedTime(new Date());
            bill.setRelationId(id);
            bill.setTransType(BillTransTypeEnum.BONUS.getValue());
            bill.setRemark("分红体现，操作人员ID为"+auth.getUid()+"操作人员名称为："+auth.getRealName()+"分红体现总额为："+issue.getPayAmount());
            agentAccountBillService.save(bill);
        } else if (auditResult.getValue().intValue() == AgentWithdrawAuditEnum.REJECT.getValue().intValue()) {
            UpdateWrapper<AgentBonus> ew = new UpdateWrapper<>();
            ew.lambda().set(AgentBonus::getOperationId, auth.getUid())
                    .set(AgentBonus::getOperationTime, LocalDateTime.now())
                    .set(AgentBonus::getOpertaionName, auth.getRealName())
                    .set(AgentBonus::getOperationStatus, AgentWithdrawAuditEnum.REJECT.getValue())
                    .set(AgentBonus::getOutBillId, null)
                    .eq(AgentBonus::getOutBillId, id);
            agentBonusService.update(ew);
        }

    }


    @Override
    public void save(SysAuth auth, AgentBonusIssueDto agentBonusIssueDto) throws Exception {
        AgentBonusIssue issue = new AgentBonusIssue();
        BeanUtils.copyProperties(agentBonusIssueDto,issue);
        AgentBonusQuery  query=new AgentBonusQuery();
        query.setAgentId(agentBonusIssueDto.getAgentId());
        List<AgentBonusVo> ttList = agentBonusService.selectList(query);
        if(ttList.size()==0){
            throw  new Exception("提现金额不足");
        }
        List<BigDecimal> bougAmoutList = ttList.stream().map(AgentBonusVo::getBonusAmount).collect(Collectors.toList());
        double sum = bougAmoutList.stream().mapToDouble(x -> x.doubleValue()).sum();
        BigDecimal bg = new BigDecimal(sum).setScale(2, RoundingMode.UP);
        issue.setPayAmount(bg);
        issue.setAmount(new BigDecimal(sum));
        issue.setAuditResult(AgentWithdrawAuditEnum.TO_AUDIT.getValue());
        issue.setCreatedTime(new Date());
        issue.setOperator(auth.getUid());
        issue.setOperationName(auth.getRealName());
        save(issue);
        UpdateWrapper<AgentBonus> ew = new UpdateWrapper<>();
        ew.lambda().set(AgentBonus::getOutBillId, issue.getId()).set(AgentBonus::getIsPay, WhetherEnum.NO.getValue()).set(AgentBonus::getOperationStatus, AgentWithdrawAuditEnum.TO_AUDIT)
                .isNull(AgentBonus::getOutBillId).eq(AgentBonus::getAgentId, agentBonusIssueDto.getAgentId());
        agentBonusService.update(ew);
    }

}
